Passa al contenuto principale

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

(Si apre in una nuova finestra)

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

Elixir

elixir programming language (Si apre in una nuova finestra)

Elixir

Paradigms (Si apre in una nuova finestra)multi-paradigm (Si apre in una nuova finestra): functional (Si apre in una nuova finestra), concurrent (Si apre in una nuova finestra), distributed (Si apre in una nuova finestra), process-oriented (Si apre in una nuova finestra)Designed by (Si apre in una nuova finestra)José ValimFirst appeared2012; 13 years agoStable release (Si apre in una nuova finestra)

1.18.4[1] (Si apre in una nuova finestra) 

Edit this on Wikidata (Si apre in una nuova finestra)

/ 21 May 2025; 4 days ago

Typing disciplinedynamic (Si apre in una nuova finestra), strong (Si apre in una nuova finestra)Platform (Si apre in una nuova finestra)Erlang (Si apre in una nuova finestra)License (Si apre in una nuova finestra)Apache License 2.0 (Si apre in una nuova finestra)[2] (Si apre in una nuova finestra)Filename extensions (Si apre in una nuova finestra).ex, .exsWebsiteelixir-lang.org (Si apre in una nuova finestra)Influenced byClojure (Si apre in una nuova finestra), Erlang (Si apre in una nuova finestra), Ruby (Si apre in una nuova finestra)InfluencedGleam (Si apre in una nuova finestra), LFE (Si apre in una nuova finestra)

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

The community organizes yearly events in the United States,[5] (Si apre in una nuova finestra) Europe,[6] (Si apre in una nuova finestra) and Japan,[7] (Si apre in una nuova finestra) as well as minor local events and conferences.[8] (Si apre in una nuova finestra)[9] (Si apre in una nuova finestra)

History

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

Elixir is aimed at large-scale sites and apps. It uses features of Ruby (Si apre in una nuova finestra), Erlang, and Clojure (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra)

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] (Si apre in una nuova finestra)

Versioning

Each of the minor versions supports a specific range of Erlang/OTP (Si apre in una nuova finestra) versions.[14] (Si apre in una nuova finestra) The current stable release version is 1.18.4[1] (Si apre in una nuova finestra) .

Features

Examples

The following examples can be run in an iex shell (Si apre in una nuova finestra) or saved in a file and run from the command line (Si apre in una nuova finestra) by typing elixir <filename>.

Classic Hello world (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra) (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 (Si apre in una nuova finestra):

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 (Si apre in una nuova finestra):

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 (Si apre in una nuova finestra) performing a task:

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

[citation needed (Si apre in una nuova finestra)]

See also

References

  1. Wlaschin, Scott (May 2013). "Railway Oriented Programming" (Si apre in una nuova finestra). F# for Fun and Profit. Archived (Si apre in una nuova finestra) from the original on 30 January 2021. Retrieved 28 February 2021.

Further reading

Programming languages (Si apre in una nuova finestra)

Authority control databases (Si apre in una nuova finestra): National

Edit this at Wikidata (Si apre in una nuova finestra)

Categories (Si apre in una nuova finestra):

Elm (programming language)

Tools

Appearance

Text

  • Small

    Standard

    Large

Width

  • Standard

    Wide

Color (beta)

  • Automatic

    Light

    Dark

From Wikipedia, the free encyclopedia

(Si apre in una nuova finestra)

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

Elm

(Si apre in una nuova finestra)

The Elm tangram

Paradigm (Si apre in una nuova finestra)functional (Si apre in una nuova finestra)FamilyHaskell (Si apre in una nuova finestra)Designed by (Si apre in una nuova finestra)Evan CzaplickiFirst appearedMarch 30, 2012; 13 years ago[1] (Si apre in una nuova finestra)Stable release (Si apre in una nuova finestra)

0.19.1 / October 21, 2019; 5 years ago[2] (Si apre in una nuova finestra)

Typing discipline (Si apre in una nuova finestra)static (Si apre in una nuova finestra), strong (Si apre in una nuova finestra), inferred (Si apre in una nuova finestra)Platform (Si apre in una nuova finestra)x86-64 (Si apre in una nuova finestra)OS (Si apre in una nuova finestra)macOS (Si apre in una nuova finestra), Windows (Si apre in una nuova finestra)License (Si apre in una nuova finestra)Permissive (Si apre in una nuova finestra) (Revised BSD (Si apre in una nuova finestra))[3] (Si apre in una nuova finestra)Filename extensions (Si apre in una nuova finestra).elmWebsiteelm-lang.org (Si apre in una nuova finestra)

Edit this at Wikidata (Si apre in una nuova finestra)

Influenced byHaskell (Si apre in una nuova finestra), Standard ML (Si apre in una nuova finestra), OCaml (Si apre in una nuova finestra), F# (Si apre in una nuova finestra)InfluencedRedux (Si apre in una nuova finestra),[4] (Si apre in una nuova finestra) Rust (Si apre in una nuova finestra),[5] (Si apre in una nuova finestra) Vue (Si apre in una nuova finestra),[6] (Si apre in una nuova finestra) Roc,[7] (Si apre in una nuova finestra) Derw,[8] (Si apre in una nuova finestra) Gren[9] (Si apre in una nuova finestra)

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

History

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

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

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 (Si apre in una nuova finestra).[22] (Si apre in una nuova finestra) As a functional language, it supports anonymous functions (Si apre in una nuova finestra), functions as arguments, and functions can return functions, the latter often by partial application of curried (Si apre in una nuova finestra) functions. Functions are called by value. Its semantics include immutable values, stateless functions (Si apre in una nuova finestra), 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 (Si apre in una nuova finestra), meaning that a value cannot be modified after it is created. Elm uses persistent data structures (Si apre in una nuova finestra) to implement its arrays, sets, and dictionaries in the standard library.[23] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra) allow the programmer to create custom types to represent data in a way that matches the problem domain.[24] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra)), 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 (Si apre in una nuova finestra): 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 (Si apre in una nuova finestra)).

Module system

Elm has a module system (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra). All libraries are versioned according to semver (Si apre in una nuova finestra), 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 (Si apre in una nuova finestra).[25] (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra) It uses a virtual DOM (Si apre in una nuova finestra) approach to make updates efficient.[27] (Si apre in una nuova finestra)

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] (Si apre in una nuova finestra)[29] (Si apre in una nuova finestra)[30] (Si apre in una nuova finestra) Czaplicki has also teased Elm Studio, a potential alternative to Lamdera, but it isn't available to the public yet.[31] (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra) table generation.[32] (Si apre in una nuova finestra)[33] (Si apre in una nuova finestra)

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

There were also some attempts in Elm versions prior to 0.19.0 to use the BEAM (Erlang virtual machine) (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra) while another one compiled it to Elixir.[37] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra) and as a TLA (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra),[39] (Si apre in una nuova finestra) which related languages Haskell (Si apre in una nuova finestra), Scala (Si apre in una nuova finestra) and PureScript (Si apre in una nuova finestra) offer, nor does Elm support the creation of type classes (Si apre in una nuova finestra).

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] (Si apre in una nuova finestra) On the other hand, implementations of TEA pattern in advanced languages like Scala (Si apre in una nuova finestra) does not suffer from such limitations and can benefit from Scala (Si apre in una nuova finestra)'s type classes, type-level (Si apre in una nuova finestra) and kind-level (Si apre in una nuova finestra) programming constructs.[41] (Si apre in una nuova finestra)

Another outcome is a large amount of boilerplate code (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra) 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" (Si apre in una nuova finestra). github.com/rtfeldman/elm-spa-example. Retrieved 30 June 2020.

External links

Haskell (Si apre in una nuova finestra) programming

Programming languages (Si apre in una nuova finestra)

Categories (Si apre in una nuova finestra):

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 (Si apre in una nuova finestra). Please help to demonstrate the notability of the topic by citing reliable secondary sources (Si apre in una nuova finestra) that are independent (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra), redirected (Si apre in una nuova finestra), or deleted (Si apre in una nuova finestra).
Find sources: "Gleam" programming language (Si apre in una nuova finestra) – news (Si apre in una nuova finestra) · newspapers (Si apre in una nuova finestra) · books (Si apre in una nuova finestra) · scholar (Si apre in una nuova finestra) · JSTOR (Si apre in una nuova finestra) (March 2024) (Learn how and when to remove this message (Si apre in una nuova finestra))

Gleam

(Si apre in una nuova finestra)

Lucy, the starfish mascot for Gleam[1] (Si apre in una nuova finestra)

Paradigm (Si apre in una nuova finestra)Multi-paradigm (Si apre in una nuova finestra): functional (Si apre in una nuova finestra), concurrent (Si apre in una nuova finestra)[2] (Si apre in una nuova finestra)Designed by (Si apre in una nuova finestra)Louis PilfoldDeveloper (Si apre in una nuova finestra)Louis PilfoldFirst appearedJune 13, 2016; 8 years agoStable release (Si apre in una nuova finestra)

1.10.0[3] (Si apre in una nuova finestra) 

Edit this on Wikidata (Si apre in una nuova finestra)

/ 14 April 2025

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

[6] (Si apre in una nuova finestra)

Gleam is a general-purpose (Si apre in una nuova finestra), concurrent (Si apre in una nuova finestra), functional (Si apre in una nuova finestra) high-level (Si apre in una nuova finestra) programming language (Si apre in una nuova finestra) that compiles to Erlang (Si apre in una nuova finestra) or JavaScript (Si apre in una nuova finestra) source code.[2] (Si apre in una nuova finestra)[7] (Si apre in una nuova finestra)[8] (Si apre in una nuova finestra)

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

History

The first numbered version of Gleam was released on April 15, 2019.[12] (Si apre in una nuova finestra) Compiling to JavaScript was introduced with version v0.16.[13] (Si apre in una nuova finestra)

In 2023 the Erlang Ecosystem Foundation funded the creation of a course for learning Gleam on the learning platform Exercism (Si apre in una nuova finestra).[14] (Si apre in una nuova finestra)

Version v1.0.0 was released on March 4, 2024.[15] (Si apre in una nuova finestra)

Features

Gleam includes the following features, many common to other functional programming languages:[8] (Si apre in una nuova finestra)

Example

A "Hello, World!" (Si apre in una nuova finestra) example:

import gleam/io

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

Gleam supports tail call (Si apre in una nuova finestra) optimization:[16] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra).[17] (Si apre in una nuova finestra) The toolchain is a single native binary executable which contains the compiler, build tool, package manager, source code formatter, and language server (Si apre in una nuova finestra). A WebAssembly (Si apre in una nuova finestra) binary containing the Gleam compiler is also available, enabling Gleam code to be compiled within a web browser.

References

  1. "gleam-lang/gleam" (Si apre in una nuova finestra). Gleam. May 6, 2024. Retrieved May 6, 2024.

External links

Stub icon (Si apre in una nuova finestra)

This programming-language (Si apre in una nuova finestra)-related article is a stub (Si apre in una nuova finestra). You can help Wikipedia by expanding it (Si apre in una nuova finestra).

Categories (Si apre in una nuova finestra):

Erlang (programming language)

Tools

Text

  • Small

    Standard

    Large

Width

  • Standard

    Wide

Color (beta)

  • Automatic

    Light

    Dark

From Wikipedia, the free encyclopedia

Erlang

(Si apre in una nuova finestra)

Paradigms (Si apre in una nuova finestra)Multi-paradigm (Si apre in una nuova finestra): concurrent (Si apre in una nuova finestra), functional (Si apre in una nuova finestra)Designed by (Si apre in una nuova finestra)

Developer (Si apre in una nuova finestra)Ericsson (Si apre in una nuova finestra)First appeared1986; 39 years agoStable release (Si apre in una nuova finestra)

27.3.4[1] (Si apre in una nuova finestra) 

Edit this on Wikidata (Si apre in una nuova finestra)

/ 8 May 2025; 9 days ago

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

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

The Erlang runtime system (Si apre in una nuova finestra) is designed for systems with these traits:

The Erlang programming language (Si apre in una nuova finestra) has immutable (Si apre in una nuova finestra) data, pattern matching (Si apre in una nuova finestra), and functional programming (Si apre in una nuova finestra).[7] (Si apre in una nuova finestra) The sequential subset of the Erlang language supports eager evaluation (Si apre in una nuova finestra), single assignment (Si apre in una nuova finestra), and dynamic typing (Si apre in una nuova finestra).

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

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

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 (Si apre in una nuova finestra) and a syllabic abbreviation (Si apre in una nuova finestra) of "Ericsson Language".[8] (Si apre in una nuova finestra)[11] (Si apre in una nuova finestra)[12] (Si apre in una nuova finestra) Erlang was designed with the aim of improving the development of telephony applications.[13] (Si apre in una nuova finestra) The initial version of Erlang was implemented in Prolog (Si apre in una nuova finestra) and was influenced by the programming language PLEX (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra) virtual machine (VM), which compiles Erlang to C using a mix of natively compiled code and threaded code (Si apre in una nuova finestra) to strike a balance between performance and disk space.[14] (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra) named AXE-N (Si apre in una nuova finestra) in 1995. As a result, Erlang was chosen for the next Asynchronous Transfer Mode (Si apre in una nuova finestra) (ATM) exchange AXD.[8] (Si apre in una nuova finestra)

(Si apre in una nuova finestra)
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] (Si apre in una nuova finestra) The ban caused Armstrong and others to make plans to leave Ericsson.[16] (Si apre in una nuova finestra) In March 1998 Ericsson announced the AXD301 switch,[8] (Si apre in una nuova finestra) containing over a million lines of Erlang and reported to achieve a high availability (Si apre in una nuova finestra) of nine "9"s (Si apre in una nuova finestra).[17] (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra) Ericsson eventually relaxed the ban and re-hired Armstrong in 2004.[16] (Si apre in una nuova finestra)

In 2006, native symmetric multiprocessing (Si apre in una nuova finestra) support was added to the runtime system and VM.[8] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra)), with data encapsulation and message passing (Si apre in una nuova finestra), but capable of changing behavior during runtime. The Erlang runtime system provides strict process isolation (Si apre in una nuova finestra) between Erlang processes (this includes data and garbage collection, separated individually by each Erlang process) and transparent communication between processes (see Location transparency (Si apre in una nuova finestra)) on different Erlang nodes (on different hosts).

Joe Armstrong, co-inventor of Erlang, summarized the principles of processes in his PhD (Si apre in una nuova finestra) thesis (Si apre in una nuova finestra):[18] (Si apre in una nuova finestra)

  • 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 (Si apre in una nuova finestra) is 'write once, run anywhere (Si apre in una nuova finestra)', then Erlang is 'write once, run forever'."[19] (Si apre in una nuova finestra)

Usage

In 2014, Ericsson (Si apre in una nuova finestra) reported Erlang was being used in its support nodes, and in GPRS (Si apre in una nuova finestra), 3G (Si apre in una nuova finestra) and LTE (Si apre in una nuova finestra) mobile networks worldwide and also by Nortel (Si apre in una nuova finestra) and Deutsche Telekom (Si apre in una nuova finestra).[20] (Si apre in una nuova finestra)

Erlang is used in RabbitMQ (Si apre in una nuova finestra). As Tim Bray (Si apre in una nuova finestra), director of Web Technologies at Sun Microsystems (Si apre in una nuova finestra), expressed in his keynote at O'Reilly Open Source Convention (Si apre in una nuova finestra) (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 (Si apre in una nuova finestra).[21] (Si apre in una nuova finestra)

It is also the language of choice for Ejabberd (Si apre in una nuova finestra) – an XMPP (Si apre in una nuova finestra) messaging server.

Elixir (Si apre in una nuova finestra) is a programming language that compiles into BEAM byte code (via Erlang Abstract Format).[22] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra) (a MasterCard company), Goldman Sachs (Si apre in una nuova finestra), Nintendo (Si apre in una nuova finestra), AdRoll, Grindr (Si apre in una nuova finestra), BT Mobile (Si apre in una nuova finestra), Samsung (Si apre in una nuova finestra), OpenX (Si apre in una nuova finestra), and SITA (Si apre in una nuova finestra).[23] (Si apre in una nuova finestra)[24] (Si apre in una nuova finestra)

Functional programming examples

Factorial

A factorial (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra):

%% 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 (Si apre in una nuova finestra) in Erlang, using list comprehension (Si apre in una nuova finestra):[25] (Si apre in una nuova finestra)

%% 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 (Si apre in una nuova finestra), 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 (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra):

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 (Si apre in una nuova finestra).)

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 (Si apre in una nuova finestra).

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 (Si apre in una nuova finestra). 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 (Si apre in una nuova finestra) are provided:

Strings

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

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 (Si apre in una nuova finestra) available.[27] (Si apre in una nuova finestra)

"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 (Si apre in una nuova finestra) used in many other programming languages. Crashes are reported like other messages, which is the only way processes can communicate with each other,[28] (Si apre in una nuova finestra) and subprocesses can be spawned cheaply (see below (Si apre in una nuova finestra)). The "let it crash" philosophy prefers that a process be completely restarted rather than trying to recover from a serious failure.[29] (Si apre in una nuova finestra) Though it still requires handling of errors, this philosophy results in less code devoted to defensive programming (Si apre in una nuova finestra) where error-handling code is highly contextual and specific.[28] (Si apre in una nuova finestra)

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 (Si apre in una nuova finestra). It has a small but powerful set of primitives to create processes and communicate among them. Erlang is conceptually similar to the language occam (Si apre in una nuova finestra), though it recasts the ideas of communicating sequential processes (Si apre in una nuova finestra) (CSP) in a functional framework and uses asynchronous message passing.[30] (Si apre in una nuova finestra) Processes are the primary means to structure an Erlang application. They are neither operating system (Si apre in una nuova finestra) processes (Si apre in una nuova finestra) nor threads (Si apre in una nuova finestra), but lightweight processes (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra).[31] (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra) (RAM; total 800 bytes/process).[32] (Si apre in una nuova finestra) Erlang has supported symmetric multiprocessing (Si apre in una nuova finestra) since release R11B of May 2006.

While threads (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra) instead of shared variables, which removes the need for explicit locks (Si apre in una nuova finestra) (a locking scheme is still used internally by the VM).[33] (Si apre in una nuova finestra)

Inter-process communication (Si apre in una nuova finestra) works via a shared-nothing (Si apre in una nuova finestra) asynchronous (Si apre in una nuova finestra) message passing (Si apre in una nuova finestra) system: every process has a "mailbox", a queue (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra)[35] (Si apre in una nuova finestra)

Implementation

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

Hot code loading and modules

Erlang supports language-level Dynamic Software Updating (Si apre in una nuova finestra). To implement this, code is loaded and managed as "module" units; the module is a compilation unit (Si apre in una nuova finestra). 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 (Si apre in una nuova finestra) 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 (Si apre in una nuova finestra), 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 (Si apre in una nuova finestra) and Deutsche Telekom (Si apre in una nuova finestra).[38] (Si apre in una nuova finestra) 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] (Si apre in una nuova finestra)[40] (Si apre in una nuova finestra) Erlang has found some use in fielding massively multiplayer online role-playing game (Si apre in una nuova finestra) (MMORPG) servers.[41] (Si apre in una nuova finestra)

See also

References

  1. Clarke, Gavin (5 February 2011). "Battlestar Galactica vets needed for online roleplay" (Si apre in una nuova finestra). Music and Media. The Reg (Si apre in una nuova finestra). Retrieved 8 February 2011.

Further reading

External links

(Si apre in una nuova finestra)

Wikimedia Commons has media related to Erlang (programming language) (Si apre in una nuova finestra).

(Si apre in una nuova finestra)

Wikibooks has a book on the topic of: Erlang Programming (Si apre in una nuova finestra)

0 commenti

Vuoi essere la prima persona a commentare?
Abbonati a Jie's stick figures e avvia una conversazione.
Sostieni