Skip to content

Elm Folha de referência

Linguagem funcional para apps web confiáveis — sem exceções em runtime.

01

Primeiros passos

Hello World

Apps Elm começam com uma função main.

elm
module Main exposing (main)

main =
  text "Hello, World!"

Tipos

Type aliases definem o formato dos records.

elm
type alias Person =
  { name : String
  , age : Int
  }

p = Person "Alice" 30

Funções

Toda função é curried; os tipos usam a notação ->.

elm
add : Int -> Int -> Int
add a b =
  a + b

Arquitetura Elm

A Elm Architecture: padrão Model-View-Update.

elm
-- Model
type alias Model = { count : Int }

-- Update
type Msg = Increment | Decrement

update msg model =
  case msg of
    Increment -> { model | count = model.count + 1 }
    Decrement -> { model | count = model.count - 1 }
02

Estruturas de dados

Listas

O módulo List tem map, filter, foldl, etc.

elm
nums = [1, 2, 3]
List.map (\n -> n * 2) nums
List.filter (\n -> n > 1) nums

Maybe

Maybe lida com null com segurança — Just ou Nothing.

elm
type Maybe a = Just a | Nothing

safeDiv a b =
  if b == 0 then Nothing else Just (a // b)

Result

Result serve para tratamento de erros — Ok ou Err.

elm
type Result e a = Ok a | Err e

parse s =
  if String.length s > 0 then Ok s else Err "empty"

Records

Acesso a records com . e atualização com |.

elm
p = { name = "Alice", age = 30 }
p.name
{ p | age = 31 }  -- update

Was this helpful?