Elm (programming language)
   HOME

TheInfoList



OR:

Elm is a
domain-specific programming language A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There are a wide variety of DSLs, ranging ...
for declaratively creating
web browser A web browser is application software for accessing websites. When a user requests a web page from a particular website, the browser retrieves its files from a web server and then displays the page on the user's screen. Browsers are used on ...
-based
graphical user interface The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
s. Elm is purely functional, and is developed with emphasis on
usability Usability can be described as the capacity of a system to provide a condition for its users to perform the tasks safely, effectively, and efficiently while enjoying the experience. In software engineering, usability is the degree to which a soft ...
, performance, and
robustness Robustness is the property of being strong and healthy in constitution. When it is transposed into a system, it refers to the ability of tolerating perturbations that might affect the system’s functional body. In the same line ''robustness'' ca ...
. It advertises "no runtime exceptions in practice", made possible by the Elm compiler's
static type checking In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
.


History

Elm was initially designed by Evan Czaplicki as his thesis in 2012. The first release of Elm came with many examples and an online editor that made it easy to try out in a
web browser A web browser is application software for accessing websites. When a user requests a web page from a particular website, the browser retrieves its files from a web server and then displays the page on the user's screen. Browsers are used on ...
. Evan joined
Prezi Prezi is a Hungarian video and visual communications software company founded in 2009 in Hungary, with offices in San Francisco, Budapest and Riga as of 2020. According to Prezi, in 2021, the software company has more than 100 million users world ...
in 2013 to work on Elm, and in 2016 moved to
NoRedInk NoRedInk (stylized as noredink) is an online web-based language-learning platform. History NoRedInk was founded by Jeff Scheur, a high school English teacher at Whitney Young Magnet High School in Chicago. After documenting years of misconcep ...
as an Open Source Engineer, also starting the Elm Software Foundation. The initial implementation of the Elm compiler targets
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScri ...
,
CSS Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS is a cornerstone techno ...
, and
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
. The set of core tools has continued to expand, now including a REPL,
package manager A package manager or package-management system is a collection of software tools that automates the process of installing, upgrading, configuring, and removing computer programs for a computer in a consistent manner. A package manager deals wi ...
, time-travelling debugger, and installers for macOS and Windows. Elm also has an ecosystem o
community created libraries
an
Ellie
an advanced online editor that allows saved work and inclusion of community libraries.


Features

Elm has a small set of language constructs, including traditional if-expressions, let-expressions for local state, and case-expressions for
pattern matching In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
. As a functional language, it supports
anonymous function In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
s, functions as arguments, and functions can return functions, the latter often by partial application of curried functions. Functions are called by value. Its semantics include immutable values, stateless functions, 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 In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3.4 ...
, meaning that a value cannot be modified after it is created. Elm uses
persistent data structure In computing, a persistent data structure or not ephemeral data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (v ...
s to implement its Arrays, Sets, and Dictionaries in the standard library.


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 allow the programmer to create custom types to represent data in a way that matches the problem domain. 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 a JavaScript's undefined or a
null pointer In computing, a null pointer or null reference is a value saved for indicating that the pointer or reference does not refer to a valid object. Programs routinely use null pointers to represent conditions such as the end of a list of unknown lengt ...
), 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 In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
: 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 Limitations section).


Module system

Elm has a
module system Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired function ...
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 th
Elm Public Library
All libraries are versioned according to semver, 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 JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
. 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. It uses a virtual
DOM Dom or DOM may refer to: People and fictional characters * Dom (given name), including fictional characters * Dom (surname) * Dom La Nena (born 1989), stage name of Brazilian-born cellist, singer and songwriter Dominique Pinto * Dom people, an et ...
approach to make updates efficient.


Backend

Elm does not officially support server-side development. The core development team does not consider it as their primary goal and prefers to focus development on the enhancement of front-end development experience. Nevertheless, there are several independent projects, which attempt to explore possibilities to use Elm for the back-end. The projects are mainly stuck on Elm version 0.18.0 since newer ones do not support "native" code and some other utilized features. There are two attempts to use Elm with BEAM (Erlang virtual machine). One of the projects executes Elm directly on the environment while another one compiles it to Elixir. Also, there was an attempt to create a back-end framework for Elm powered by Node.js infrastructure. None of the projects are production-ready.


The Elm Architecture

The Elm Architecture is a 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. 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.


Limitations

Elm does not support higher-kinded polymorphism, which related languages
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
and
PureScript PureScript is a strongly-typed, purely-functional programming language that compiles to JavaScript. It can be used to develop web applications, server side apps, and also desktop applications with use of Electron. Its syntax is mostly comparabl ...
offer, nor does Elm support the creation of
type classes In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
. 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. Another outcome is a large amount of
boilerplate code In computer programming, boilerplate code, or simply boilerplate, are sections of code that are repeated in multiple places with little to no variation. When using languages that are considered ''verbose'', the programmer must write a lot of boile ...
in medium to large size projects as illustrated by the author of "Elm in Action" in their single page application example with almost identical fragments being repeated in update, view, subscriptions, route parsing and building functions.


Example code

-- This is a single line comment. -- 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 `\ rg-> xpression 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 : book = -- 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

*
PureScript PureScript is a strongly-typed, purely-functional programming language that compiles to JavaScript. It can be used to develop web applications, server side apps, and also desktop applications with use of Electron. Its syntax is mostly comparabl ...
: a strongly-typed, purely-functional programming language that compiles to JavaScript *
Reason Reason is the capacity of consciously applying logic by drawing conclusions from new or existing information, with the aim of seeking the truth. It is closely associated with such characteristically human activities as philosophy, science, ...
: A syntax extension and toolchain for
OCaml OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
that can also
transpile A source-to-source translator, source-to-source compiler (S2S compiler), transcompiler, or transpiler is a type of translator that takes the source code of a program written in a programming language as its input and produces an equivalent sou ...
to JavaScript


References


External links

* {{Programming languages 2012 software Domain-specific programming languages Functional languages Pattern matching programming languages Programming languages created in 2012 Source-to-source compilers Statically typed programming languages Web frameworks