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

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
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
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
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43757 214
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
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
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement