Skip to content

Elm チートシート

実行時例外のない、信頼性の高い Web アプリのための関数型言語。

01

はじめに

Hello World

Elm アプリは main 関数から始まります。

elm
module Main exposing (main)

main =
  text "Hello, World!"

型

type alias でレコードの形を定義します。

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

p = Person "Alice" 30

関数

すべての関数はカリー化され、型は -> 記法で表します。

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

Elm アーキテクチャ

The Elm Architecture: 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

データ構造

リスト

List モジュールには map、filter、foldl などがあります。

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

Maybe

Maybe は null を安全に扱います — Just か Nothing のどちらかです。

elm
type Maybe a = Just a | Nothing

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

Result

Result はエラーハンドリング用です — Ok か Err のどちらかです。

elm
type Result e a = Ok a | Err e

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

レコード

レコードは . でアクセスし、| で更新します。

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

Was this helpful?