Gleam Functional Utils Library

Small, composable functional helpers for Gleam.

Installation

If you have Gleam installed, you can add this package to your project:

gleam add fp_utils

Package Version Hex Docs

Then, you can start using the functions in your Gleam code:

import fp_utils/func
import fp_utils/option
import fp_utils/result
import fp_utils/list
import fp_utils/predicate

Philosophy

This library provides focused, small, and reusable helpers for Gleam’s functional programming style. It works with core types like Result, Option, List, and Dict (though Dict helpers are a future extension) rather than introducing new abstractions. The emphasis is on clarity and composability, aiming to feel like “missing pieces” from the Gleam standard library.

Core Modules & Ideas

fp/result

Helpers for Result(a, e):

fp/option

Helpers for Option(a):

fp/list

Higher-order list helpers:

fp/func

Function-level helpers:

fp/predicate

Helpers for working with boolean functions:

Example Usage

import fp_utils/result
import fp_utils/list
import fp_utils/func
import fp_utils/option
import gleam/option as gleam_option

pub fn example() -> Bool {
  [1, 2, 3, 4]
  |> list.flat_map(fn(x) { [x, x * 2] })
  |> list.filter(fn(x) { x > 2 })
  |> list.uniq()
  |> list.any(fn(x) { x == 6 }) // true
}

pub fn safe_divide(a: Int, b: Int) -> Result(Int, String) {
  case b == 0 {
    True -> Error("division by zero")
    False -> Ok(a / b)
  }
}

pub fn demo() -> Int {
  safe_divide(10, 2)
  |> result.map(fn(x) { x * 2 })
  |> result.unwrap_or(0) // 10
}

// New Option utilities in action
pub fn option_pipeline_demo() -> String {
  gleam_option.Some(42)
  |> option.filter(fn(x) { x > 0 })
  |> option.map(fn(x) { x * 2 })
  |> option.or(gleam_option.Some(0))
  |> option.to_result("missing value")
  |> result.map(fn(x) { "Result: " <> int.to_string(x) })
  |> result.unwrap_or("No result")
  // "Result: 84"
}

// Combining Options ergonomically
pub fn combine_options_demo() -> gleam_option.Option(Int) {
  let first = gleam_option.Some(10)
  let second = gleam_option.Some(5)

  option.zip_with(first, second, fn(a, b) { a + b })
  |> option.filter(fn(sum) { sum > 10 })
  // Some(15)
}

Naming & Packaging

The package name is fp_utils. Modules are organized under fp_utils/, e.g., fp_utils/result, fp_utils/option.

Future Extensions

Links

Search Document