neuone

neuone

Overview

I want to convert a Swift enumerated type into something similar in Elixir. I do not want to use any external libraries as I wanted to see how far I can take this.

Here is the Swift code I want to convert to Elixir:

note: about indirect keyword

the indirect keyword reference themselves, and they are called “indirect” because they modify the storage mechanism in Swift to accommodate any size. Without indirection, an enum that references itself could become infinitely sized, which is not possible. To handle self-referencing associated values, we mark the enum as indirect.

Example 1

  • Using :atom keys to define a constant key, which are similar to Enumerated types in other languages according to my research.
  • Error correction is implemented.
  • Added the ability to view all possible types with all_cases\0.
defmodule Example1.Result do
  defstruct [:type, :score]

  @types ~w(player cpu tie previous)a

  @doc """
  Returns a list of the possible result types

  ## Example

      iex> Result.all_cases()
      [:player, :cpu, :tie, :previous]
  """
  def all_cases(), do: @types

  @doc """
  Returns a result type when a `type` is passed.

  ## Examples
      iex> Result.score(:player)
      %Result{type: :player, score: 0}

      iex> Result.score(:player, 100)
      %Result{type: :player, score: 100}

      iex> Result.score(:cpu, 100)
      %Result{type: :cpu, score: 100}

      iex> Result.score(:tie, 100)
      %Result{type: :tie, score: 100}

      iex> Result.score(:previous, %Result.score(:player, 100))
      %Result{type: :previous, score: %Result{type: :player, score: 100}}
  """
  def score(type, score \\ 0)
  def score(type, score) when type in @types, do: put_score(type, score)
  def score(type, _score), do: raise(ArgumentError, message: "You cannot use #{inspect(type)}")

  defp put_score(:player, score), do: %__MODULE__{type: :player, score: score}
  defp put_score(:cpu, score), do: %__MODULE__{type: :cpu, score: score}
  defp put_score(:tie, score), do: %__MODULE__{type: :tie, score: score}

  defp put_score(:previous, previous = %__MODULE__{type: type}) when type in @types,
    do: %__MODULE__{type: :previous, score: previous}

  defp put_score(:previous, _previous),
    do:
      raise(ArgumentError,
        message:
          "You must pass in a previous Result that has a known type of :player, :cpu, :tie, :previous"
      )
end

Example 2

  • Using a Sum Type (or tagged unions or discriminated unions) so that I can enumerate all the possiblities that the type can take. Using tuples.
  • The functions player/1, cpu/1, tie/1, and previous/1 in the Result module act as constructors for the Sum Type of @type result
  • I was reading up on typespecs and changed my approach.
defmodule Example2.Result do
  @type score :: Integer.t()
  @type result ::
          {:player, score}
          | {:cpu, score}
          | {:tie, score}
          | {:previous, result}

  defstruct [:value]

  @type t() :: %__MODULE__{
          value: result
        }

  @spec player(score) :: Result.t()
  def player(score), do: put_value(:player, score)

  @spec cpu(score) :: Result.t()
  def cpu(score), do: put_value(:cpu, score)

  @spec tie(score) :: Result.t()
  def tie(score), do: put_value(:tie, score)

  @spec previous(Result.t()) :: Result.t()
  def previous(my_result = %__MODULE__{}), do: put_value(:previous, my_result)
  defp put_value(type, score), do: %__MODULE__{value: {type, score}}
end

Example 3

  • Elixir allows nesting modules and module names are also atoms, as mentioned in this source.
  • This approach is similar to the first one, but utilizes nested modules to explore what gets returned at the call site.
defmodule Example3.Result do
  defmodule Player do
    defstruct [:score]
  end

  defmodule CPU do
    defstruct [:score]
  end

  defmodule Tie do
    defstruct [:score]
  end

  defmodule Previous do
    defstruct [:result]
  end

  @types ~w(player cpu tie previous)a

  alias __MODULE__.{
    Player,
    CPU,
    Tie,
    Previous
  }

  @doc """
  Returns a result type when a `type` is passed.

  ## Examples
      iex> Result.cpu(:player)
      %Result.Player{score: 0}

      iex> Result.score(:player, 100)
      %Result.Player{score: 100}

      iex> Result.score(:cpu, 100)
      %Result.CPU{score: 0}

      iex> Result.score(:tie, 100)
      %Result.Tie{score: 100}

      iex> Result.score :previous, %Result.Player{score: 100}
      %Result.Previous{result: %Result.Player{score: 100}}
  """

  def score(type, score \\ 0)
  def score(type, score) when type in @types, do: put_score(type, score)
  def score(type, _score), do: raise(ArgumentError, message: "You cannot use #{inspect(type)}")

  defp put_score(:player, score), do: %Player{score: score}
  defp put_score(:cpu, score), do: %CPU{score: score}
  defp put_score(:tie, score), do: %Tie{score: score}
  defp put_score(:previous, previous), do: put_previous(previous)
  defp put_previous(previous = %Player{}), do: %Previous{result: previous}
  defp put_previous(previous = %CPU{}), do: %Previous{result: previous}
  defp put_previous(previous = %Tie{}), do: %Previous{result: previous}

  defp put_previous(_previous),
    do: raise(ArgumentError, message: "You must pass in a previous Result.Previous")
end

Usage and Ergonomics

Example 1 - is idiomatic (I think)

iex> Result.score(:player, 100)
 %Result{type: :player, score: 100}

Example 2 - improves ergonomics with a constructor.

iex> Result.player(100)
 %Result{value: {:player, 100}}

Example 3 - uses nested modules to future-proof the struct, allowing additional information to be added.

iex> Result.score(:player, 100)
 %Result.Player{score: 100}

Conclusion

My goal is to understand what is the ideal approach to this in Elixir.

  • Example 2 is growing on me as the solution. I have to get used to returning a tuple as my final value, but that’s okay.
  • I do like name spacing my modules like in Example 3.

Thanks for reading any feedback?

Showing Posts 1 to 2

dimitarvp

dimitarvp

I always liked #3 but I found it overkill in practice so nowadays I use #2. It’s simple, readable and you can add Dialyzer typespecs like you did.

To me it’s the most practical option. You can always go ham with dedicated modules for each enum value and standardized constructors etc. but it’s important to not have the line count of your project explode.

aenglisc

aenglisc

Defining a struct for every type gets too big too quickly. Unless your goal is to use protocols (which I see little reason for here) I would say it’s more effort than it’s worth.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews