neuone

neuone

Converting an enumerated type from swift into an equivalent in elixir

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?

Most Liked

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.

Where Next?

Popular in Questions Top

chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement