myronmarston

myronmarston

Typespecs - best way to spec keyword lists?

The Elixir Typespec docs show the following syntax for keyword lists in typespecs:

# ...
| [key: type]                   # keyword lists
# ...

It’s nice to have a syntax that is like the literal keyword list syntax, but there are a number of open questions here:

  • Given that lists are ordered, and [a: 1, b: 2] = kw_list only matches if kw_list is in that order…is a typespec like [a: integer, b: integer] only satisfied by a keyword list in that order?
  • Are all keys required? Or are all keys optional?

Elsewhere I’ve seen keyword lists type spec’d doing something like:

@type option :: {:name, String.t} | {:max, pos_integer} | {:min, pos_integer}
@type options :: [option]

This is very clear: I can tell that order does not manner, and no options are required.

Can someone from Elixir Core weigh in? I’m getting dialyzer running on an existing application and am trying to understand the right way to spec keyword lists (and also to be sure I’m satisfying the typespecs in Elixir itself).

Thanks!

Marked As Solved

michalmuskala

michalmuskala

The longer form of separated option and options type has a very important advantage - it’s composable. It allows to write code like this:

@type option :: {:my_option, String.t} | GenServer.option

@spec start_link([option]) :: GenServer.on_start
def start_link(opts) do
  {my_opts, gen_server_opts} = Keyword.split(opts, [:my_option])
  GenServer.start_link(__MODULE__, my_opts, gen_server_opts)
end

That kind of extension is not possible when you have a full list type.

23
Post #3

Also Liked

jwarlander

jwarlander

Some quick tests:

defmodule TypeSpecDemo do
  @moduledoc """
  Documentation for TypeSpecDemo.
  """


  @spec hello([bar: String.t, baaz: String.t]) :: {:world, list}
  def hello(opts \\ []) do
    {:world, opts}
  end

  # correct usage
  def default_to_empty_list, do: hello()
  def call_with_empty_list, do: hello([])
  def first_key_only, do: hello(bar: "bar")
  def second_key_only, do: hello([baaz: "baaz"])
  def both_keys_in_order, do: hello([bar: "bar", baaz: "baaz"])
  def both_keys_reversed, do: hello([baaz: "baaz", bar: "bar"])

  # incorrect usage
  def bad_arg, do: hello("world")
  def unknown_key, do: hello(foo: "foo")
  def wrong_value, do: hello(baaz: 15)
end

Setting up according to instructions for Dialyxir, and then running mix dialyzer, gives me the following output:

Compiling 1 file (.ex)
Checking PLT...
[:compiler, :elixir, :kernel, :logger, :stdlib]
PLT is up to date!
Starting Dialyzer
dialyzer --no_check_plt --plt /home/johwar/src/type_spec_demo/_build/dev/dialyxir_erlang-18.2.1_elixir-1.4.0-rc.1_deps-dev.plt /home/johwar/src/type_spec_demo/_build/dev/lib/type_spec_demo/ebin
  Proceeding with analysis...
type_spec_demo.ex:21: Function bad_arg/0 has no local return
type_spec_demo.ex:21: The call 'Elixir.TypeSpecDemo':hello(<<_:40>>) breaks the contract ([{'bar','Elixir.String':t()} | {'baaz','Elixir.String':t()}]) -> {'world',[any()]}
type_spec_demo.ex:22: Function unknown_key/0 has no local return
type_spec_demo.ex:22: The call 'Elixir.TypeSpecDemo':hello([{'foo',<<_:24>>},...]) breaks the contract ([{'bar','Elixir.String':t()} | {'baaz','Elixir.String':t()}]) -> {'world',[any()]}
type_spec_demo.ex:23: Function wrong_value/0 has no local return
type_spec_demo.ex:23: The call 'Elixir.TypeSpecDemo':hello([{'baaz',15},...]) breaks the contract ([{'bar','Elixir.String':t()} | {'baaz','Elixir.String':t()}]) -> {'world',[any()]}
 done in 0m1.04s
done (warnings were emitted)

It seems that the shorter, documented syntax of [key1: type1, key2: type2] actually means the same as [{:key1, type1} | {:key2, type2}]. Order does not matter and an empty list is OK, but unknown keys are rejected.

Maybe there are situations where it’s useful to have a type for the individual allowed keyword entries I guess, like option in our example, but until I run across that I’d probably use the shorter syntax.

11
Post #2
nathanl

nathanl

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
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

We're in Beta

About us Mission Statement