[Proposal] Support steps in typespecs

35 views
Skip to first unread message

jonar...@gmail.com

unread,
Apr 13, 2021, 11:02:59 AM4/13/21
to elixir-lang-core
While working with the v1.12.0 rc0 release, I wrote the following typespec:

@spec my_fun(1..10//2) :: boolean()

which resulted in the following error:

== Compilation error in file lib/foobar.ex ==
** (CompileError) lib/foobar.ex:6: type ..///3 undefined (no such type in Foobar)

My confusion stemmed from my belief that ranges in typespecs were interpreted by Elixir and expanded at compile time (e.g. 1..10 to 1|2|3|4|5|...) since the syntax (first..last) matches the Elixir range syntax and Erlang has no native ranges. Of course, this was wrong because while Erlang doesn't have ranges, Dialyzer does.

While I can't think of the last time I wanted the contract of my function to be "only accepts odd integers between 1 and 100", it also seems like a curious omission. From the perspective of someone with good knowledge of Elixir but limited knowledge of Erlang and Dialyzer, I had originally believed that this was some kind of mistake or oversight.

There also might be a use-case in providing additional information to Dialyzer, such as:
@spec odd?(1..10//2) :: true
@spec odd?(2..10//2) :: false

Would it be worth taking a type such as 1..10//2 and compiling it to 1|3|5|7|9 for Dialyzer?

José Valim

unread,
Apr 13, 2021, 11:17:35 AM4/13/21
to elixir-l...@googlegroups.com
Given Dialyzer does not natively support stepped ranges, I don't think we should emulate them and have 1..10//1 and 1..10//2 to two very distinct things. :(

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/d9415490-4285-48fe-a863-4d778ccc962an%40googlegroups.com.

Felipe Stival

unread,
Apr 13, 2021, 12:12:39 PM4/13/21
to elixir-lang-core
Shouldn't we support custom step types (like we do for first and last) like in this diff?

José Valim

unread,
Apr 13, 2021, 12:17:08 PM4/13/21
to elixir-l...@googlegroups.com
1..2 in typespecs does not mean a range %Range{first: 1, last: 2}, rather an integer from 1 to 2.

Reply all
Reply to author
Forward
0 new messages