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

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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
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
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
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
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
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
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement