sfrances

sfrances

Using module attributes in typespec definitions to reduce duplication?

Hi

I’m trying to use module attributes in my typespec, but I get errors when I do this:

defmodule KitchenCalculator do
  @ml :milliliter
  @cup :cup
  @fluid_ounce :fluid_ounce
  @tsp :teaspoon
  @tbsp :tablespoon

  @type unit :: @ml | @cup | @fluid_ounce | @tsp | @tbsp

  # More stuff here
end

I get the error:

** (CompileError) lib/kitchen_calculator.ex:8: type ml/0 undefined (no such type in KitchenCalculator)
    (elixir 1.12.2) lib/kernel/typespec.ex:925: Kernel.Typespec.compile_error/2
    (stdlib 3.15.2) lists.erl:1358: :lists.mapfoldl/3
    (elixir 1.12.2) lib/kernel/typespec.ex:834: Kernel.Typespec.typespec/4
    (stdlib 3.15.2) lists.erl:1358: :lists.mapfoldl/3
    (elixir 1.12.2) lib/kernel/typespec.ex:464: Kernel.Typespec.typespec/4
    (elixir 1.12.2) lib/kernel/typespec.ex:307: Kernel.Typespec.translate_type/2
    (stdlib 3.15.2) lists.erl:1358: :lists.mapfoldl/3
    (elixir 1.12.2) lib/kernel/typespec.ex:235: Kernel.Typespec.translate_typespecs_for_module/2

I use the module attributes later on, to reduce duplication and chance of errors via typos when typing out atoms. Is there any way to achieve this, or do I just live with the minor duplication?

Marked As Solved

kip

kip

ex_cldr Core Team

You can do it like this:

defmodule KitchenCalculator do
  @ml :milliliter
  @cup :cup
  @fluid_ounce :fluid_ounce
  @tsp :teaspoon
  @tbsp :tablespoon

  types = Enum.reduce([@ml, @cup, @fluid_ounce, @tsp, @tbsp], &({:|, [], [&1, &2]}))
  @type unit :: unquote(types)

  # More stuff here
end

You could of course encapsulate the Enum.reduce/2 into a macro and reuse it that way.

iex> t KitchenCalculator.unit
@type unit() :: :tablespoon | :teaspoon | :fluid_ounce | :cup | :milliliter

BTW, if you’re spending a lot of time with units, unit math and unit conversions, and potentially unit serialisation and localization, you might find ex_cldr_units helpful (I’m the author).

Also Liked

kip

kip

ex_cldr Core Team

In the few occasions when I’ve used the technique above I have done it directly. In my cases, building a macro just to do that hasn’t been important and I felt it would actually make the code more obscure. By having the Metaprogramming line directly above, it makes it easy for “future me” to work out what I was thinking.

I’m sure you’ve heard the aphorism in Elixir-land, “first rule of macros is don’t use macros”.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement