Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Gleam Type System

БесплатноБез исполняемых скриптовНе проверен

Use when gleam's type system including algebraic data types, custom types, pattern matching, generic types, type inference, opaque types, exhaustive checking…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Gleam Type System

Introduction

Gleam is a statically-typed functional language that compiles to Erlang and JavaScript, bringing modern type safety to the BEAM ecosystem. Its type system prevents entire categories of runtime errors while maintaining the concurrency and fault-tolerance benefits of the Erlang VM.

The type system features algebraic data types, parametric polymorphism, type inference, exhaustive pattern matching, and no null values. Every value is typed, and the compiler enforces type safety at compile time, eliminating common bugs before code runs.

This skill covers custom types and ADTs, pattern matching, generic types, Result and Option types, type aliases, opaque types, type inference, and patterns for type-safe error handling on the BEAM.

Custom Types and Records

Custom types define structured data with named fields, providing type-safe access and pattern matching.

// Simple custom type (record)
pub type User {
  User(name: String, age: Int, email: String)
}

// Creating instances
pub fn create_user() -> User {
  User(name: "Alice", age: 30, email: "[email protected]")
}

// Accessing fields
pub fn get_user_name(user: User) -> String {
  user.name
}

pub fn get_user_age(user: User) -> Int {
  user.age
}

// Updating records (immutable)
pub fn birthday(user: User) -> User {
  User(..user, age: user.age + 1)
}

pub fn change_email(user: User, new_email: String) -> User {
  User(..user, email: new_email)
}

// Multiple constructors
pub type Shape {
  Circle(radius: Float)
  Rectangle(width: Float, height: Float)
  Triangle(base: Float, height: Float)
}

pub fn area(shape: Shape) -> Float {
  case shape {
    Circle(radius) -> 3.14159 *. radius *. radius
    Rectangle(width, height) -> width *. height
    Triangle(base, height) -> base *. height /. 2.0
  }
}

// Tuple structs (unlabeled fields)
pub type Point {
  Point(Float, Float)
}

pub fn distance(p1: Point, p2: Point) -> Float {
  let Point(x1, y1) = p1
  let Point(x2, y2) = p2
  let dx = x2 -. x1
  let dy = y2 -. y1
  float.square_root(dx *. dx +. dy *. dy)
}

// Nested custom types
pub type Address {
  Address(street: String, city: String, zip: String)
}

pub type Person {
  Person(name: String, age: Int, address: Address)
}

pub fn get_city(person: Person) -> String {
  person.address.city
}

// Generic custom types
pub type Box(a) {
  Box(value: a)
}

pub fn box_map(box: Box(a), f: fn(a) -> b) -> Box(b) {
  Box(value: f(box.value))
}

pub fn unbox(box: Box(a)) -> a {
  box.value
}

// Recursive types
pub type Tree(a) {
  Leaf(value: a)
  Branch(left: Tree(a), right: Tree(a))
}

pub fn tree_depth(tree: Tree(a)) -> Int {
  case tree {
    Leaf(_) -> 1
    Branch(left, right) -> 1 + int.max(tree_depth(left), tree_depth(right))
  }
}

// Phantom types for type-safe APIs
pub type Validated
pub type Unvalidated

pub type Email(state) {
  Email(value: String)
}

pub fn create_email(value: String) -> Email(Unvalidated) {
  Email(value: value)
}

pub fn validate_email(email: Email(Unvalidated)) ->
  Result(Email(Validated), String) {
  case string.contains(email.value, "@") {
    True -> Ok(Email(value: email.value))
    False -> Error("Invalid email format")
  }
}

pub fn send_email(email: Email(Validated)) -> Nil {
  // Only validated emails can be sent
  io.println("Sending email to: " <> email.value)
}

Custom types provide named, type-safe data structures with exhaustive pattern matching guarantees.

Algebraic Data Types

ADTs model data with multiple variants, enabling exhaustive pattern matching and making invalid states unrepresentable.

// Sum type (enum)
pub type Status {
  Pending
  Approved
  Rejected
}

pub fn status_to_string(status: Status) -> String {
  case status {
    Pending -> "Pending"
    Approved -> "Approved"
    Rejected -> "Rejected"
  }
}

// Result type (built-in ADT)
pub type Result(ok, error) {
  Ok(ok)
  Error(error)
}

pub fn parse_int(str: String) -> Result(Int, String) {
  case int.parse(str) {
    Ok(n) -> Ok(n)
    Error(_) -> Error("Not a valid integer")
  }
}

pub fn handle_result(result: Result(Int, String)) -> String {
  case result {
    Ok(n) -> "Got number: " <> int.to_string(n)
    Error(msg) -> "Error: " <> msg
  }
}

// Option type pattern
pub type Option(a) {
  Some(a)
  None
}

pub fn find_user(id: Int) -> Option(User) {
  case id {
    1 -> Some(User(name: "Alice", age: 30, email: "[email protected]"))
    _ -> None
  }
}

pub fn option_map(opt: Option(a), f: fn(a) -> b) -> Option(b) {
  case opt {
    Some(value) -> Some(f(value))
    None -> None
  }
}

pub fn option_unwrap_or(opt: Option(a), default: a) -> a {
  case opt {
    Some(value) -> value
    None -> default
  }
}

// Complex ADTs
pub type HttpResponse {
  Ok200(body: String)
  Created201(body: String, location: String)
  BadRequest400(message: String)
  NotFound404
  ServerError500(message: String)
}

pub fn handle_response(response: HttpResponse) -> String {
  case response {
    Ok200(body)
Полный SKILL.md на GitHub

Установить Gleam Type System в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Gleam Type System?

Use when gleam's type system including algebraic data types, custom types, pattern matching, generic types, type inference, opaque types, exhaustive checking, and functional error handling for building type-safe Erlang VM applications.

Как установить скилл Gleam Type System?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Gleam Type System запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Gleam Type System с