AshSumType (ash_sum_type v1.0.4)

Copy Markdown

A Spark DSL for defining Ash types that behave like algebraic sum types.

Each module that uses AshSumType becomes an Ash type. Values are represented in memory as tuples whose first element is the variant tag (must be an atom):

defmodule DrinkSize do
  use AshSumType, variants: [:small, :large]
end

defmodule Result do
  use AshSumType

  variant :ok do
    field :value, :integer
  end

  variant :error do
    field :message, :string, allow_nil?: true
  end
end

Result.new(:ok, value: 1)
# {:ok, {:ok, 1}}

Result.new({:ok, 1})
# {:ok, {:ok, 1}}

This library stores sum-type values in the database as maps using the reserved __variant__ key, while exposing atoms/tuples in memory.

fields values are not nullable by default.

Options

  • :variants (list of atom/0) - Shorthand nullary variants to define when using AshSumType. The default value is [].

  • :extensions (list of module that adopts Spark.Dsl.Extension) - A list of DSL extensions to add to the Spark.Dsl

  • :otp_app (atom/0) - The otp_app to use for any application configurable options

  • :fragments (list of module/0) - Fragments to include in the Spark.Dsl. See the fragments guide for more.